import { PageContainer } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import { Card, Form, Input, Button, message, Select, InputNumber, TreeSelect, Modal, Tooltip } from 'antd';
import { useNavigate } from 'react-router-dom';
import { createStyles } from 'antd-style';
import { resourceAdd, resourceListTree } from '@/services/system/resource';
import * as Icons from '@ant-design/icons';
import { SearchOutlined } from '@ant-design/icons';

const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
    background: '#f5f5f5',
    minHeight: 'calc(100vh - 48px)',
  },
  card: {
    borderRadius: '8px',
    boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03)',
  },
  form: {
    maxWidth: '800px',
    margin: '0 auto',
  },
  formItem: {
    marginBottom: '24px',
    '& .ant-form-item-label': {
      fontWeight: 500,
    },
  },
  buttonGroup: {
    display: 'flex',
    justifyContent: 'center',
    gap: '16px',
    marginTop: '40px',
  },
  formLayout: {
    display: 'grid',
    gridTemplateColumns: '1fr 1fr',
    gap: '24px',
  },
  fullWidth: {
    gridColumn: '1 / -1',
  },
}));

// 图标中文映射
const iconNameMap: Record<string, string> = {
  'UserOutlined': '用户',
  'TeamOutlined': '团队',
  'FileOutlined': '文件',
  'FolderOutlined': '文件夹',
  'DashboardOutlined': '仪表盘',
  'SettingOutlined': '设置',
  'MenuOutlined': '菜单',
  'AppstoreOutlined': '应用',
  'HomeOutlined': '首页',
  'SecurityScanOutlined': '安全',
  'SafetyCertificateOutlined': '认证',
  'KeyOutlined': '密钥',
  'ApiOutlined': '接口',
  'DatabaseOutlined': '数据库',
  'ClusterOutlined': '集群',
  'GroupOutlined': '分组',
  'UserSwitchOutlined': '切换用户',
  'SolutionOutlined': '解决方案',
  'AuditOutlined': '审计',
  'BarsOutlined': '列表',
  'OrderedListOutlined': '有序列表',
  'UnorderedListOutlined': '无序列表',
  'ProfileOutlined': '档案',
  'ProjectOutlined': '项目',
  'LogoutOutlined': '退出',
  'LoginOutlined': '登录',
  // 可以继续添加更多图标的中文映射
};

// 获取所有图标并添加中文名称
const allIcons = Object.keys(Icons)
  .filter(key => key.endsWith('Outlined'))
  .map(key => ({
    name: key,
    icon: Icons[key],
    label: iconNameMap[key] || key.replace('Outlined', ''), // 如果没有中文映射，则使用英文名去掉Outlined后缀
  }));

const IconSelect: React.FC<{
  value?: string;
  onChange?: (value: string) => void;
}> = ({ value, onChange }) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedIcon, setSelectedIcon] = useState(value);

  const filteredIcons = allIcons.filter(icon =>
    icon.name.toLowerCase().includes(searchText.toLowerCase()) ||
    icon.label.includes(searchText) // 支持中文搜索
  );

  const handleIconClick = (iconName: string) => {
    setSelectedIcon(iconName);
    onChange?.(iconName);
    setIsModalVisible(false);
  };

  const IconComponent = value ? Icons[value] : SearchOutlined;

  return (
    <>
      <Input
        value={value ? `${iconNameMap[value] || value.replace('Outlined', '')} (${value})` : ''}
        readOnly
        placeholder="点击选择图标"
        onClick={() => setIsModalVisible(true)}
        prefix={<IconComponent />}
        style={{ cursor: 'pointer' }}
      />
      <Modal
        title="选择图标"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        width={800}
        footer={null}
      >
        <Input
          prefix={<SearchOutlined />}
          placeholder="搜索图标（支持中文）"
          value={searchText}
          onChange={e => setSearchText(e.target.value)}
          style={{ marginBottom: 16 }}
        />
        <div style={{
          height: '60vh',
          overflow: 'auto',
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(100px, 1fr))',
          gap: '8px',
        }}>
          {filteredIcons.map(({ name, icon: Icon, label }) => (
            <Tooltip title={`${label} (${name})`} key={name}>
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  padding: '8px',
                  cursor: 'pointer',
                  border: selectedIcon === name ? '2px solid #1890ff' : '2px solid transparent',
                  borderRadius: '4px',
                  transition: 'all 0.3s',
                }}
                onClick={() => handleIconClick(name)}
              >
                <Icon style={{ fontSize: '24px' }} />
                <div style={{
                  fontSize: '12px',
                  marginTop: '4px',
                  width: '100%',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  textAlign: 'center',
                }}>
                  {label}
                </div>
              </div>
            </Tooltip>
          ))}
        </div>
      </Modal>
    </>
  );
};

const ResourceManageAdd: React.FC = () => {
  const { styles } = useStyles();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [treeData, setTreeData] = useState<any[]>([]);

  // 获取资源树数据
  useEffect(() => {
    const fetchResourceTree = async () => {
      try {
        const response = await resourceListTree();
        if (response.code === 200) {
          // 添加一个根节点选项
          const rootNode = {
            title: '顶级资源',
            value: '0',
            key: '0',
            children: response.data,
          };
          setTreeData([rootNode]);
        } else {
          message.error(response.msg || '获取资源树失败');
        }
      } catch (error) {
        console.error('获取资源树失败:', error);
        message.error('获取资源树失败');
      }
    };

    fetchResourceTree();
  }, []);

  const onFinish = async (values: any) => {
    try {
      const response = await resourceAdd(values);
      if (response.code === 200) {
        message.success('新增资源成功');
        navigate('/system/resourcemanage');
      } else {
        message.error(response.msg || '新增资源失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('新增资源失败');
    }
  };

  const handleCancel = () => {
    navigate('/system/resourcemanage');
  };

  return (
    <PageContainer>
      <div className={styles.container}>
        <Card className={styles.card}>
          <Form
            form={form}
            layout="vertical"
            onFinish={onFinish}
            className={styles.form}
          >
            <div className={styles.formLayout}>
              <Form.Item
                name="resourceName"
                label="资源名称"
                rules={[{ required: true, message: '请输入资源名称' }]}
                className={styles.formItem}
              >
                <Input placeholder="请输入资源名称" />
              </Form.Item>

              <Form.Item
                name="alias"
                label="资源别名"
                rules={[{ required: true, message: '请输入资源别名' }]}
                className={styles.formItem}
              >
                <Input placeholder="请输入资源别名，如：userManage" />
              </Form.Item>

              <Form.Item
                name="resourceParentId"
                label="上级资源"
                rules={[{ required: true, message: '请选择上级资源' }]}
                className={styles.formItem}
              >
                <TreeSelect
                  showSearch
                  style={{ width: '100%' }}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  placeholder="请选择上级资源"
                  allowClear
                  treeDefaultExpandAll
                  treeData={treeData}
                  fieldNames={{
                    label: 'resourceName',
                    value: 'id',
                    children: 'children',
                  }}
                  treeNodeFilterProp="resourceName"
                />
              </Form.Item>

              <Form.Item
                name="path"
                label="路由地址"
                rules={[{ required: true, message: '请输入路由地址' }]}
                className={styles.formItem}
              >
                <Input placeholder="请输入路由地址，如：/sys/user" />
              </Form.Item>

              <Form.Item
                name="resourceType"
                label="资源类型"
                rules={[{ required: true, message: '请选择资源类型' }]}
                className={styles.formItem}
              >
                <Select placeholder="请选择资源类型">
                  <Select.Option value="menu">菜单</Select.Option>
                  <Select.Option value="page">页面</Select.Option>
                  <Select.Option value="button">按钮</Select.Option>
                  {/* <Select.Option value="api">接口</Select.Option> */}
                </Select>
              </Form.Item>

              <Form.Item
                name="iconPath"
                label="资源图标"
                rules={[{ required: true, message: '请选择资源图标' }]}
                className={styles.formItem}
              >
                <IconSelect />
              </Form.Item>

              <Form.Item
                name="sort"
                label="排序"
                rules={[{ required: true, message: '请输入排序号' }]}
                className={styles.formItem}
              >
                <InputNumber
                  min={1}
                  max={999}
                  style={{ width: '100%' }}
                  placeholder="请输入排序号，数值越小越靠前"
                />
              </Form.Item>

              <Form.Item
                name="isNewWindow"
                label="是否显示"
                rules={[{ required: true, message: '请选择是否显示' }]}
                className={styles.formItem}
              >
                <Select placeholder="请选择是否显示">
                  <Select.Option value={1}>是</Select.Option>
                  <Select.Option value={0}>否</Select.Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="remark"
                label="资源备注"
                className={`${styles.formItem} ${styles.fullWidth}`}
              >
                <Input.TextArea rows={4} placeholder="请输入资源备注" />
              </Form.Item>
            </div>

            <div className={styles.buttonGroup}>
              <Button onClick={handleCancel}>
                返回
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </div>
          </Form>
        </Card>
      </div>
    </PageContainer>
  );
};

export default ResourceManageAdd;
